package com.bub.pay.framework.common.util;


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.ResolvableType;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static ConfigurableApplicationContext getConfigurableApplicationContext(){
        return (ConfigurableApplicationContext) getApplicationContext();
    }

    public static BeanDefinitionRegistry getBeanDefinitionRegistry(){
        return (BeanDefinitionRegistry) getConfigurableApplicationContext().getBeanFactory();
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz, Object... args) {
        return getApplicationContext().getBean(clazz, args);
    }

    public static <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType) {
        return getApplicationContext().getBeanProvider(requiredType);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    /// 获取当前环境
    public static String getActiveProfile() {
        return getApplicationContext().getEnvironment().getActiveProfiles()[0];
    }

}
